package com.ghsc.ghxc.jsb.ui.message.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.annotation.NonNull
import androidx.core.net.toUri
import androidx.fragment.app.FragmentManager
import com.alivc.auicommon.common.base.callback.Callbacks
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.InteractionError
import com.aliyun.aliinteraction.uikit.uibase.util.LastLiveSp
import com.aliyun.auiappserver.AppServerTokenManager
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.config.AliLiveMediaStreamOptions
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.KeyboardUtils
import com.cn.appcore.utils.Preference
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.AcivityYxMyChatBinding
import com.ghsc.ghxc.jsb.ui.live.activity.RedExtensionIndexActivity
import com.ghsc.ghxc.jsb.ui.live.bean.MaterialChildInfoBean
import com.ghsc.ghxc.jsb.ui.live.view.CustLiveProtoType
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusRedAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareLiveAttachment
import com.ghsc.ghxc.jsb.ui.live.view.gif.GiftPopup
import com.ghsc.ghxc.jsb.ui.message.view.CustMsgType
import com.ghsc.ghxc.jsb.ui.message.view.NewRobRedPopView
import com.ghsc.ghxc.jsb.ui.message.view.gif.ImGiftPopup
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.msg.model.IMMessage
import com.netease.nimlib.sdk.uinfo.UserService
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import com.netease.yunxin.kit.chatkit.repo.ChatRepo
import com.netease.yunxin.kit.chatkit.ui.ChatKitClient
import com.netease.yunxin.kit.chatkit.ui.ChatUIConfig
import com.netease.yunxin.kit.chatkit.ui.IChatInputMenu
import com.netease.yunxin.kit.chatkit.ui.builder.IChatViewCustom
import com.netease.yunxin.kit.chatkit.ui.common.MessageHelper
import com.netease.yunxin.kit.chatkit.ui.dialog.ChatBaseForwardSelectDialog
import com.netease.yunxin.kit.chatkit.ui.interfaces.IMessageItemClickListener
import com.netease.yunxin.kit.chatkit.ui.model.ChatMessageBean
import com.netease.yunxin.kit.chatkit.ui.normal.ChatMessageForwardSelectDialog
import com.netease.yunxin.kit.chatkit.ui.normal.builder.P2PChatFragmentBuilder
import com.netease.yunxin.kit.chatkit.ui.normal.page.fragment.ChatP2PFragment
import com.netease.yunxin.kit.chatkit.ui.normal.view.ChatView
import com.netease.yunxin.kit.chatkit.ui.normal.view.CustTextCallback
import com.netease.yunxin.kit.chatkit.ui.view.input.ActionConstants
import com.netease.yunxin.kit.chatkit.ui.view.message.MessageProperties
import com.netease.yunxin.kit.chatkit.ui.view.popmenu.ChatPopMenuAction
import com.netease.yunxin.kit.chatkit.ui.view.popmenu.IChatPopMenu
import com.netease.yunxin.kit.chatkit.ui.view.popmenu.IChatPopMenuClickListener
import com.netease.yunxin.kit.chatkit.utils.SendMediaHelper
import com.netease.yunxin.kit.common.ui.action.ActionItem
import com.netease.yunxin.kit.corekit.im.custom.CustomAttachment
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.netease.yunxin.kit.corekit.im.provider.FetchCallbackImpl
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant
import com.permissionx.guolindev.PermissionX
import java.io.File

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：MyChatP2PActivity
 * 创建时间：2024/5/7 22:40
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class MyChatP2PActivity  : BaseVMActivity<MyChatViewModel, AcivityYxMyChatBinding>() ,
    CustTextCallback {
    override fun attachLayoutRes(): Int {
        return R.layout.acivity_yx_my_chat
    }

    override fun attachVMClass(): Class<MyChatViewModel>? {
        return MyChatViewModel::class.java
    }
    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }

    var chatFragment: ChatP2PFragment?=null
    var userInfoBean : NimUserInfo?=null

    val userMyId:String by Preference(HttpConstant.USER_ID, "")
    val CHOOSE_PHOTO_2 = 1002

    private var themeId = 0


    override fun initView() {
        KeyboardUtils.fixAndroidBug5497(this)
        themeId= R.style.picture_default_style
        val userInfo = intent.getSerializableExtra(RouterConstant.CHAT_KRY) as UserInfo?
        val accId = intent.getStringExtra(RouterConstant.CHAT_ID_KRY)
        if (userInfo == null && TextUtils.isEmpty(accId)) {
            finish()
        }

        val chatUIConfig = ChatUIConfig()
        if (!TextUtils.isEmpty(accId)){
             if (accId==CustKey.CHAT_SYSY_ID){
                //如果是系统消息 隐藏ui
                binding.topRightView.visibility= View.GONE
                chatUIConfig.chatViewCustom=
                    IChatViewCustom { layout ->
                        if (layout is ChatView){
                            val frameLayout = layout.inputView
                            frameLayout.visibility = View.GONE
                        }
                    }
            }
            var mlistId= arrayListOf<String>()
            mlistId.add(accId!!)
            NIMClient.getService(UserService::class.java).fetchUserInfo(mlistId).setCallback(object :
                RequestCallback<List<NimUserInfo>> {
                override fun onSuccess(result: List<NimUserInfo>?) {
                    if (result!=null){
                        userInfoBean=result[0]
                        if (userInfoBean!=null)
                            binding.topTitle.text=userInfoBean!!.name

                    }
                }

                override fun onFailed(code: Int) {
                }

                override fun onException(exception: Throwable?) {
                }

            })


        }else{
            if (userInfo!=null)
                userInfoBean=userInfo
            binding.topTitle.text=userInfoBean!!.name
            if (userInfoBean!!.account==CustKey.CHAT_SYSY_ID){
                //如果是系统消息 隐藏ui
                binding.topRightView.visibility= View.GONE
                chatUIConfig.chatViewCustom=
                    IChatViewCustom { layout ->
                        if (layout is ChatView){
                            val frameLayout = layout.inputView
                            frameLayout.visibility = View.GONE
                        }
                    }
            }
        }


        ///
        chatUIConfig.messageProperties = MessageProperties()
        chatUIConfig.messageProperties.showTitleBar = false
        chatUIConfig.messageProperties.showP2pMessageStatus=true
        chatUIConfig.messageItemClickListener =object : IMessageItemClickListener {
            override fun onMessageLongClick(
                view: View?,
                position: Int,
                messageInfo: ChatMessageBean?
            ): Boolean {
                return false
            }


            override fun onMessageClick(
                view: View?,
                position: Int,
                messageInfo: ChatMessageBean?
            ): Boolean {

                return false
            }

            override fun onUserIconClick(
                view: View?,
                position: Int,
                messageInfo: ChatMessageBean?
            ): Boolean {
                loge("会话消息头像点击事件===")
                messageInfo?.let {
                    if (it.messageData.message.sessionType== SessionTypeEnum.P2P){
                        if (userInfoBean!!.account!=CustKey.CHAT_SYSY_ID){
                            //单聊
                            var  bundle = Bundle()
                            bundle.putString("userIdTa",it.messageData.message.sessionId)
                            startActivity(ChatSetSingleActivity().javaClass,bundle)
                        }
                    }
                }

                return true

            }
        }
        //长安消息事件
        chatUIConfig!!.popMenuClickListener =object : IChatPopMenuClickListener {
            override fun onCopy(messageInfo: ChatMessageBean?): Boolean {
//                if (messageInfo!!.viewType==100){
//                    val msg: IMMessage = messageInfo.messageData.message
//                    if (msg.attachment is CustomAttachment) {
//                        val bean =msg.attachment as CustomAttachment
//                        if (bean.type==CustMsgType.CUST_IM_SHARE_LIVE){
//                            val custLiveBean =msg.attachment as CusShareLiveAttachment
//                            val text = custLiveBean.nickName+"正在直播，欢迎来观看 "+custLiveBean.liveUrl
//                            copyToClipboard(this@MyChatP2PActivity,text)
//                            return true
//                        }else return false
//                    }else return false
//                }else   return false
                return false
            }

            //转发
            override fun onForward(messageInfo: ChatMessageBean?): Boolean {
                val dialog = ChatMessageForwardSelectDialog()
                dialog.setSelectedCallback(
                    object : ChatBaseForwardSelectDialog.ForwardTypeSelectedCallback {
                        override fun onTeamSelected() {
                            if (messageInfo!!.messageData.message.attachment is CustomAttachment) {
                                val bean =messageInfo.messageData.message.attachment as CustomAttachment
                                if (bean.type==CustMsgType.CUST_IM_CUST_GIF){
                                    showToast("礼物消息不能转发")
                                    return
                                }
                            }
                            var  bundle = Bundle()
                            bundle.putInt("type",2)
                            bundle.putSerializable("messageInfo",messageInfo!!.messageData)
                            startActivity(YXFriendsListActivity().javaClass,bundle)
                        }

                        override fun onP2PSelected() {
                            if (messageInfo!!.messageData.message.attachment is CustomAttachment) {
                                val bean =messageInfo.messageData.message.attachment as CustomAttachment
                                if (bean.type==CustMsgType.CUST_IM_CUST_GIF){
                                    showToast("礼物消息不能转发")
                                    return
                                }
                            }
                            var  bundle = Bundle()
                            bundle.putInt("type",1)
                            bundle.putSerializable("messageInfo",messageInfo!!.messageData)
                            startActivity(YXFriendsListActivity().javaClass,bundle)
                        }
                    })
                dialog.show(supportFragmentManager, "ChatMessageForwardSelectDialog")
                return true

            }
        }
        //去除消息长按菜单的【标记】按钮
        chatUIConfig.chatPopMenu = object : IChatPopMenu {
            @NonNull
            override fun customizePopMenu(
                menuList: MutableList<ChatPopMenuAction>, messageBean: ChatMessageBean
            ): List<ChatPopMenuAction> {
                if (menuList != null) {
                    for (index in menuList.indices.reversed()) {
                        if (TextUtils.equals(
                                menuList[index].action,
                                ActionConstants.POP_ACTION_PIN
                            )
                        ) {
                            menuList.removeAt(index)
                            break
                        }
                    }
                }
                return menuList
            }
        }
        chatUIConfig.chatInputMenu = object : IChatInputMenu {
            override fun customizeInputBar(actionItemList: MutableList<ActionItem>): List<ActionItem> {
                //个性化配置输入框下方按钮，actionItemList传递默认配置的四个按钮：语音、表情、图片和更多。
                //您可以根据自己的需求修改actionItemList的数量和顺序，ChatKit-UI会按照您的返回结果展示。
                val nullItemList=actionItemList
                nullItemList.add(ActionItem(ActionConstants.ACTION_TYPE_CUST_GIF,  R.drawable.ic_chat_gift_icon))
                return    nullItemList
            }

            override fun onInputClick(context: Context?, view: View?, action: String?): Boolean {
                loge("xxxx==="+action)
                if (action== ActionConstants.ACTION_TYPE_ALBUM){
                    showPictures(CHOOSE_PHOTO_2)
                    return true
                }else  if (action== ActionConstants.ACTION_TYPE_CUST_GIF){
                    XPopup.Builder(this@MyChatP2PActivity)
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .customHostLifecycle(lifecycle)
                        .dismissOnTouchOutside(true)
                        .hasShadowBg(false)
                        .enableDrag(false)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        //这个属性必须加，不然GiftFragment出问题
                        .isViewMode(true)
                        .asCustom(
                            ImGiftPopup(this@MyChatP2PActivity, userInfoBean!!.account!!)
                        )
                        .show()
                    return true
                }else  return false


            }


            override fun customizeInputMore(actionItemList: MutableList<ActionItem>): List<ActionItem> {
                //个性化配置更多面板中按钮，actionItemList传递默认配置的四个按钮：拍摄、文件、位置和音视频通话。
                val list =actionItemList
                val beanLocation = list.find { it.action == ActionConstants.ACTION_TYPE_LOCATION }
                val beanCall= list.find { it.action == ActionConstants.ACTION_TYPE_VIDEO_CALL }
                if (beanLocation!=null)
                    list.remove(beanLocation)
                if (beanCall!=null)
                    list.remove(beanCall)
//                list.add(ActionItem("custom_red", R.drawable.icon_im_red, R.string.im_str_red))
                return list
            }

            override fun onCustomInputClick(
                context: Context?,
                view: View?,
                action: String?
            ): Boolean {
//                if (action=="custom_red"){
//                    val  sessionId = if(!TextUtils.isEmpty(accId)) accId else  userInfo!!.account
//                    if (sessionId!= CustKey.CHAT_SYSY_ID){
//                        var  bundle =Bundle()
//                        bundle.putInt("type",1)
//                        bundle.putString("targetId",sessionId)
//                        startActivity(RedExtensionActivity().javaClass,bundle)
//                    }
//                    return true
//                }else {
//                    return false
//                }
                return false
            }
        }
        ChatKitClient.setChatUIConfig(chatUIConfig)

        //加载界面
        val fragmentManager: FragmentManager = supportFragmentManager
        //创建ChatP2PFragment
        val fragmentBuilder = P2PChatFragmentBuilder()
        chatFragment= fragmentBuilder.build()
        val bundle = Bundle()
        bundle.putSerializable(RouterConstant.CHAT_ID_KRY, accId)
        bundle.putSerializable(RouterConstant.CHAT_KRY, userInfo)
        val message = intent.getSerializableExtra(RouterConstant.KEY_MESSAGE) as IMMessage?
        if (message != null) {
            bundle.putSerializable(RouterConstant.KEY_MESSAGE, message)
        }
        chatFragment!!.arguments = bundle
        //将ChatP2PFragment加载到Activity中
        fragmentManager
            .beginTransaction()
            .add(R.id.chat_container, chatFragment!!)
            .commitAllowingStateLoss()



        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustMsgType.CUST_RED_RESU_DEL && rxBusBean.sign == CustMsgType.CUST_RED_RESU_DEL -> {
                        //刷新ui
                       finish()
                    }
                    rxBusBean.id == CustSignKey.CHAT_RED_SEE_LEFT && rxBusBean.sign == CustSignKey.CHAT_RED_SEE_LEFT -> {
                        /** 红包点击 **/
                        //需要判断。是否领取
                        val currentMessage =rxBusBean.anyBean as ChatMessageBean
                        val bean = currentMessage.messageData.message.attachment as CusRedAttachment
                        if (currentMessage.messageData.message.localExtension!=null){
                            loge("获取红包自定义show"+currentMessage.messageData.message.localExtension.toString())
                            var map: HashMap<String, String> =currentMessage.messageData.message.localExtension as HashMap<String, String>
                            if (!TextUtils.isEmpty(map[UserManager.getUserId()])){
                                var  bundle = Bundle()
                                bundle.putString("packetid",bean.id.toString())
                                startActivity(RedExtensionIndexActivity().javaClass,bundle)
                            }else{
                                showRobRedView(currentMessage)
                            }
                        }else {
                            //没有领取
                            showRobRedView(currentMessage)
                        }
                    }
                    rxBusBean.id == CustMsgType.CUST_RED_RESU && rxBusBean.sign == CustMsgType.CUST_RED_RESU -> {
                        //刷新ui
                        val messageBean =rxBusBean.anyBean as IMMessage
                        if (chatFragment!=null)
                            chatFragment!!.chatView.messageListView
                                .updateMessage(messageBean,
                                    ActionConstants.PAYLOAD_STATUS)
                    }
                    rxBusBean.id == CustSignKey.CHAT_LIVE_URL && rxBusBean.sign == CustSignKey.CHAT_LIVE_URL -> {
                        val bean =rxBusBean.anyBean as CusShareLiveAttachment
                        PermissionX.init(this@MyChatP2PActivity)
                            .permissions(
                                Manifest.permission.CAMERA,
                                Manifest.permission.RECORD_AUDIO,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .request { allGranted, _, _ ->
                                showLoading()
                                getInitStatus(bean.liveId, bean.anchorId)
                            }
                    }
                    rxBusBean.id == CustSignKey.LIVE_START && rxBusBean.sign == CustSignKey.LIVE_START -> {
                        showToast("该直播已结束...")
                    }
                    rxBusBean.id == CustSignKey.IM_DELETE_INFO && rxBusBean.sign == CustSignKey.IM_DELETE_INFO -> {
                        // 关闭会话
                        finish()
                    }
                    rxBusBean.id == CustKey.IM_IMG_VIDEO && rxBusBean.sign == CustKey.IM_IMG_VIDEO -> {
                        // 查看图片和视频 分享素材
                        var position= rxBusBean.index
                        var imgVideo= rxBusBean.anyBean as MutableList<MaterialChildInfoBean>
                        var selectList: MutableList<LocalMedia> = ArrayList()
                        for( i in imgVideo.indices){
                            val localMedia = LocalMedia()
                            localMedia.path = imgVideo[i].url
                            localMedia.mimeType= if(imgVideo[i].type==1)  PictureMimeType.MIME_TYPE_VIDEO  else  PictureMimeType.MIME_TYPE_IMAGE
                            selectList.add(localMedia)
                        }
                        // 预览图片 可自定长按保存路径
                        PictureSelector.create(this)
                            .themeStyle(R.style.picture_default_style) // xml设置主题
                            //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                            //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                            .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                            .openExternalPreview(position, selectList)
                    }
                }
            }

    }


    override fun onStart() {
        super.onStart()
        if (chatFragment!=null){
            if (chatFragment!!.messageBottomLayout !=null)
                chatFragment!!.messageBottomLayout.setTextCallback(this)
        }
    }
    override fun initClickListener() {
        super.initClickListener()
        binding.topLeftView.setSingleClickListener {
            finish()
        }
        binding.topRightView.setSingleClickListener {
            var  bundle = Bundle()
            bundle.putString("userIdTa",userInfoBean!!.account)
            startActivity(ChatSetSingleActivity().javaClass,bundle)
        }
    }


    /** 抢红包 **/
    private fun showRobRedView(bean:ChatMessageBean){
        XPopup.Builder(this)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
            .customHostLifecycle(lifecycle)
            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
            //这个属性必须加，不然GiftFragment出问题
            .isViewMode(true)
            .dismissOnTouchOutside(true)
            .dismissOnBackPressed(true)
            .asCustom(NewRobRedPopView(this,bean))
            .show()

    }

    private fun getInitStatus(liveId: String, anchorId: String) {
        if ( !TextUtils.isEmpty(AppServerTokenManager.getAppServerToken()) && !TextUtils.isEmpty(
                Const.getUserId())) {
            gotoLivePage(liveId, anchorId)
        } else {
            showLoading()
            //todo 直播请求自己的接口 登录 login 参数 request
            AppServerTokenManager.login(userMyId, userMyId,
                object : InteractionCallback<Void?> {
                    override fun onSuccess(data: Void?) {
                        loge("直播登录=")
                        dismissLoading()
                        Const.setUserId(UserManager.getUserId())
//                                    UserHelper.storeUserId(UserManager.getUserId())
                        if (!TextUtils.isEmpty(Const.getUserId())){
                            gotoLivePage(liveId, anchorId)
                        }
                    }

                    override fun onError(interactionError: InteractionError?) {
                        dismissLoading()
                        showToast("服务器出错...")
                    }
                })
        }
    }
    /**
     * 跳转直播页面
     *
     * @param liveId   直播Id
     * @param anchorId 主播Id
     */
    private fun gotoLivePage(liveId: String?, anchorId: String) {
        val param = CustLiveProtoType.OpenLiveParam()
        param.liveId = liveId
        param.nick = UserManager.getUserName()
        param.userAvatar= UserManager.getUserHead()
        val callback = Callbacks.Lambda<String> { success, data, errorMsg ->
            if (success) {
                // 成功后, 记录该场直播, 便于下次快速进入
                val lastLiveSp = LastLiveSp.INSTANCE
                lastLiveSp.lastLiveId = liveId ?: data
                lastLiveSp.lastLiveAnchorId = anchorId
            } else {
                showToast(errorMsg)
            }
        }
        val isAnchor = TextUtils.equals(Const.getUserId(), anchorId)
        if (isAnchor) {
            // 主播端: 开启直播
            param.role = LiveRole.ANCHOR

            // 推流支持动态配置
            val pusherOptions = AliLiveMediaStreamOptions()
            param.mediaPusherOptions = pusherOptions
        } else {
            // 观众端: 观看直播
            param.role = LiveRole.AUDIENCE
        }
        dismissLoading()
        if (isAnchor) {
//            LivePrototype.getInstancece().setup(requireActivity(), param, callback)
            CustLiveProtoType.instance!!.setup(this, param, callback)
        } else {
//            LivePrototype.getInstance().setup(requireActivity(), param, callback)
            CustLiveProtoType.instance!!.setup(this, param, callback)
        }
    }

    private fun showPictures(index: Int) {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofAll())
            .loadImageEngine(GlideEngine.createGlideEngine())
            .theme(themeId)
            .selectionMode(PictureConfig.SINGLE)
            .imageSpanCount(4)
            .previewImage(true)
            .isCamera(true)
            .enableCrop(false) // 是否裁剪
            .compress(true) // 是否压缩
            .freeStyleCropEnabled(true) // 裁剪框是否可拖拽
            .scaleEnabled(true)
//            .withAspectRatio(16, 9)
//                .cropWH(345,128)// 裁剪宽高比，设置如果大于图片本身宽高则无效
//                .cropImageWideHigh()//
            .minimumCompressSize(100) // 小于100kb的图片不压缩
            .forResult(index)

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_OK -> when (requestCode) {
                CHOOSE_PHOTO_2 -> {
                    // 图片选择结果回调

                    val selectBack = PictureSelector.obtainMultipleResult(data)
                    for (media in selectBack) {
                        Log.i("图片-----》", media.path)
                        val  pathBack= if (media.isCut && !media.isCompressed) {
                            // 裁剪过
                            media.cutPath
                        } else if (media.isCompressed || media.isCut && media.isCompressed) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            media.compressPath
                        } else {
                            // 原图
                            media.path
                        }
                        if (media.mimeType==PictureMimeType.MIME_TYPE_VIDEO){
                            SendMediaHelper.handleVideo(pathBack.toUri(),
                                object : SendMediaHelper.Callback {
                                    override fun onFinish(file: File) {
                                        val mmr = MediaMetadataRetriever()
                                        try {
                                            mmr.setDataSource(file.path)
                                            val duration =
                                                mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
                                            var width =
                                                mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
                                            var height =
                                                mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
                                            val orientation =
                                                mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)
                                            if (TextUtils.equals(orientation, "90")) {
                                                val local = width!!
                                                width = height
                                                height = local
                                            }
                                            val message = MessageBuilder.createVideoMessage(
                                                userInfoBean!!.account,
                                                SessionTypeEnum.P2P,
                                                file,
                                                duration!!.toLong(),
                                                width!!.toInt(),
                                                height!!.toInt(),
                                                file.name
                                            )
                                            ChatRepo.sendMessage(
                                                message,
                                                false,
                                                object : FetchCallbackImpl<Void>() {
                                                    override fun onFailed(code: Int) {
                                                        loge("xxxx===" + code)
                                                        if (code == 7101) {
                                                            MessageHelper.saveLocalBlackTipMessageAndNotify(
                                                                message
                                                            )
                                                        }
                                                    }
                                                })
                                        } catch (e: Exception) {
                                            e.printStackTrace()
                                        } finally {
                                            mmr.release()
                                        }
                                    }

                                })
                        }else {
                            val imageMsg =
                                MessageBuilder.createImageMessage(userInfoBean!!.account, SessionTypeEnum.P2P, File(pathBack))
                            ChatRepo.sendMessage(
                                imageMsg,
                                false,
                                object : FetchCallbackImpl<Void>() {
                                    override fun onFailed(code: Int) {
                                        if (code == 7101) {
                                            MessageHelper.saveLocalBlackTipMessageAndNotify(imageMsg)
                                        }
                                    }
                                })
                        }

                    }
                }
            }
            else -> {
            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MyChatP2PActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@MyChatP2PActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
        }
    }

    var msg :String =""
    var replyMessage :ChatMessageBean? = null
    override fun onTextReceived(msg: String?, replyMessage: ChatMessageBean?) {
        this.replyMessage=replyMessage
//        mViewModel.onYxChatAuthMethod("")
    }
}